package com.bingxue.edu.management.education.service;

import com.bingxue.edu.framework.common.model.PageQuery;
import com.bingxue.edu.framework.common.util.ValidationUtils;
import com.bingxue.edu.framework.mybatis.base.BaseService;
import com.bingxue.edu.framework.mybatis.query.QueryBuilder;
import com.bingxue.edu.management.education.mapper.ArrangeTemplateMapper;
import com.bingxue.edu.management.education.model.entity.ArrangeLesson;
import com.bingxue.edu.management.education.model.entity.ArrangeTemplate;
import com.bingxue.edu.management.education.model.query.ArrangeTemplateQuery;
import com.bingxue.edu.management.education.model.req.ArrangeLessonReq;
import com.bingxue.edu.management.education.model.req.ArrangeTemplateReq;
import com.bingxue.edu.management.education.model.resp.ArrangeTemplateDetailResp;
import com.bingxue.edu.management.education.model.resp.ArrangeTemplateResp;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;

import static com.bingxue.edu.management.education.model.entity.table.ArrangeLessonTableDef.ARRANGE_LESSON;

/**
 * 排课模板实现类
 * @author zq
 * @since 2024/08/21
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ArrangeTemplateService extends BaseService<ArrangeTemplateMapper, ArrangeTemplate> {

    private final ArrangeLessonService arrangeLessonService;

    public Page<ArrangeTemplateResp> getTemplatePage(ArrangeTemplateQuery query, PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryBuilder.build(query, pageQuery);
        return this.pageAs(pageQuery.toPage(), queryWrapper, ArrangeTemplateResp.class);
    }


    public ArrangeTemplateDetailResp getDetailById(String templateId) {
        return this.getMapper().selectOneWithRelationsByIdAs(templateId, ArrangeTemplateDetailResp.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void create(ArrangeTemplateReq req) {
        // 创建排课模板
        ArrangeTemplate arrangeTemplate = this.copy(req);
        // 设置起止时间
        this.updateDateRange(req, arrangeTemplate);
        this.save(arrangeTemplate);

        // 创建模板课次
        String templateId = arrangeTemplate.getId();
        createArrangeLessonList(req.getArrangeLessonList(), templateId);

        log.info("创建排课模板成功：{}", arrangeTemplate);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateById(ArrangeTemplateReq req, String id) {
        ArrangeTemplate obj = this.getById(id);
        ValidationUtils.throwIfNull(obj,"模板不存在");
        // 更新排课模板
        ArrangeTemplate arrangeTemplate = this.copy(req);
        arrangeTemplate.setId(id);
        this.updateDateRange(req, arrangeTemplate);
        this.updateById(arrangeTemplate);
        // 根据templateId删除原先的课次
        arrangeLessonService.remove(ARRANGE_LESSON.TEMPLATE_ID.eq(id));
        // 批量新增课次
        createArrangeLessonList(req.getArrangeLessonList(), id);
        log.info("更新模板成功, {}", arrangeTemplate);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        // 1.删除模板数据
        this.removeById(id);
        // 2.删除模板数据对应的课次
        arrangeLessonService.remove(ARRANGE_LESSON.TEMPLATE_ID.eq(id));
        log.info("删除模板成功, {}", id);
    }


    /**
     * 设置起止时间
     */
    private void updateDateRange(ArrangeTemplateReq req, ArrangeTemplate arrangeTemplate) {
        ValidationUtils.throwIf(req.getArrangeLessonList().isEmpty(),"课次数量不能为空");
        List<ArrangeLessonReq> lessonList = req.getArrangeLessonList();
        lessonList.sort(Comparator.comparing(ArrangeLessonReq::getLessonIndex));
        arrangeTemplate.setStartDate(lessonList.get(0).getLessonDate());
        arrangeTemplate.setEndDate(lessonList.get(lessonList.size() - 1).getLessonDate());
        arrangeTemplate.setLessonCount(req.getArrangeLessonList().size());
    }

    /**
     * 创建模板课次列表
     */
    private void createArrangeLessonList(List<ArrangeLessonReq> req, String templateId){
        List<ArrangeLesson> arrangeLessonLis = req.stream().map(item -> {
            ArrangeLesson arrangeLesson = new ArrangeLesson();
            arrangeLesson.setLessonIndex(item.getLessonIndex());
            arrangeLesson.setLessonDate(item.getLessonDate());
            arrangeLesson.setTemplateId(templateId);
            return arrangeLesson;
        }).toList();
        arrangeLessonService.saveBatch(arrangeLessonLis);
    }

}
